#include "Log.h"

#include <stdarg.h>
#include <stdio.h>
#include <string.h>

void timestampf(char *buffer, char *format) {
    time_t now = {0};
    char time_buffer[40] = {0};

    struct tm* time_struct;
    struct timeval tv;
    struct timezone tz;
    int length = 0;
    
    time(&now);
    gettimeofday(&tv, &tz);
    time_struct = localtime((const time_t *)&now);
    length = strftime(time_buffer, 40, format, time_struct);
    strcpy(buffer, time_buffer);
}

void timestamp(char *buffer) {
    timestampf(buffer, TIME_STAMP_FORMAT);

    char usec[100] = {0};
    struct timeval tv;
    struct timezone tz;
    gettimeofday(&tv, &tz);
    sprintf(usec, ".%03ld", (tv.tv_usec/1000));
    strcat(buffer, usec);
}

void printflog(char *level, const char *format, ...) {
    char tf[100] = {0};
    timestamp(tf);

    char log[1000] = {0};
    va_list vlist;
    va_start(vlist, format);
    fprintf(stdout, "[%s] %s - ", tf, level);
    // vasprintf(char **restrict, const char *restrict, va_list)
    int erro = vprintf(format, vlist);
    fprintf(stdout, "\n");
    va_end(vlist);
}

// simple
void printlog(char *msg) {
    if (msg != NULL) {
        printflog(LOG_INFO, "%s", msg);
    }
}